/**
 * Created by Void on 2017/7/13.
 *
 *  网络请求服务类
 */

import {Injectable} from '@angular/core';
import {
    Http, Headers, RequestOptions, URLSearchParams, RequestOptionsArgs, RequestMethod
} from '@angular/http';
import 'rxjs/add/operator/toPromise';
import {Observable} from "rxjs";
import {NativeServiceC} from "./NativeServiceC";
import {AlertController} from "ionic-angular";
import {APP_SERVE_URL} from "./Constants";

@Injectable()
export class HttpService {

    constructor(public http:Http,
                private nativeService:NativeServiceC,
                private alertCtrl:AlertController) {
    }

    public request(url:string, options:RequestOptionsArgs) { //:Observable<Response>
        url = HttpService.formatUrl(url);
        this.optionsAddToken(options);
        return Observable.create(observer => {
            this.nativeService.showLoading();
            this.http.request(url, options)
                .map(res => res.json())
                .subscribe(res => {
                    if (res.code == 200 || res.error_code == 200) {
                        observer.next(res.data);
                    } else {
                        observer.error(res);
                        this.requestFailed(url, options, {status: res.code});//处理请求失败
                    }
                }, err => {
                    this.requestFailed(url, options, err);//处理请求失败
                    observer.error(err);
                });
        });
    }

    public get(url:string, paramMap:any = null) { //:Observable<Response>
        return this.request(url, new RequestOptions({
            method: RequestMethod.Get,
            search: HttpService.buildURLSearchParams(paramMap)
        }));
    }

    public post(url:string, body:any = null):Observable<any> {
        return this.request(url, new RequestOptions({
            method: RequestMethod.Post,
            body: body,
            headers: new Headers({
                'Content-Type': 'application/x-www-form-urlencoded'
            })
        }));
    }

    public jsonRpc(model:string, method:string, args:any, kwargs?:any):Observable<any> {

        kwargs = kwargs || {};
        kwargs.context = kwargs.context || {};
        Object.assign(kwargs.context, {
            lang: "zh_CN",
            tz:"Asia/Hong_Kong"
        });

        let params = {
            model: model,
            method: method,
            args: args,
            kwargs: kwargs,
        };
        return this.request("http://101.200.124.206:4713/web/dataset/call_kw", new RequestOptions({
            method: RequestMethod.Post,
            body: this.jsonrpcBuildSender(params),
            headers: new Headers({
                'Content-Type': 'application/json; charset=UTF-8',
                "X-Openerp-Session-Id": 'a6e881e882dff5ca206b916753601873690cfbab',
                // "Authorization": "Basic " + btoa(`${null}`)
            })
        }));
    }

    public jsonRpcLogin(login: string, password: string,db?: string){
        db = db || 'hospital-saas';
        let params = {
            db : db,
            login : login,
            password : password
        };
        return this.request("http://101.200.124.206:4713/web/session/authenticate",{
            method:RequestMethod.Post,
            body: this.jsonrpcBuildSender(params),
        });
    }

    private jsonrpcBuildSender(params:Object):Object{
        let option = {
            jsonrpc: "2.0",
            method: "call",
            params: params, // payload
            id:new Date().getTime()
        };
        return option;
    }


    /**
     * 将对象转为查询参数
     * @param paramMap
     * @returns {URLSearchParams}
     */
    private static buildURLSearchParams(paramMap):URLSearchParams {
        let params = new URLSearchParams();
        if (!paramMap) {
            return params;
        }
        for (let key in paramMap) {
            let val = paramMap[key];

            // todo 暂时不处理时间
            // if (val instanceof Date) {
            //     val = Utils.dateFormat(val, 'yyyy-MM-dd hh:mm:ss')
            // }
            params.set(key, val);
        }
        return params;
    }

    /**
     * 处理请求失败事件
     * @param url
     * @param options
     * @param err
     */
    private requestFailed(url:string, options:RequestOptionsArgs, err):void {
        this.nativeService.hideLoading();
        console.log('%c 请求失败 %c', 'color:red', '', 'url', url, 'options', options, 'err', err);
        console.log(JSON.stringify(err));
        let msg = '请求发生异常', status = err.status;
        if (!this.nativeService.isConnecting()) {
            msg = '请求失败，请连接网络';
        } else {
            if (status === 0) {
                msg = '请求失败，请求响应出错';
            } else if (status === 404) {
                msg = '请求失败，未找到请求地址';
            } else if (status === 500) {
                msg = '请求失败，服务器出错，请稍后再试';
            }
        }
        this.alertCtrl.create({
            title: msg,
            subTitle: '状态码:' + status,
            buttons: [{text: '确定'}]
        }).present();
    }

    /**
     * url中如果有双斜杠替换为单斜杠
     * 如:http://88.128.18.144:8080//api//demo. 替换后http://88.128.18.144:8080/api/demo
     * @param url
     * @returns {string}
     */
    private static formatUrl(url:string):string {
        if (url.indexOf('http://') == -1 && url.indexOf('https://') == -1) {
            url = APP_SERVE_URL + url;
        }
        let index = url.indexOf('//') + 2;
        return url.substring(0, index) + url.substring(index).replace(/\/\//g, '/');
    }

    private optionsAddToken(options:RequestOptionsArgs):void {
        let token = 'TOKEN'; //this.globalData.token;
        if (options.headers) {
            options.headers.append('token', token);
        } else {
            options.headers = new Headers({
                'token': token
            });
        }
    }
}

